package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.List;

/**
 * @Name AddressServiceImpl
 * @Author stella
 * @Date 2023-03-09 2:36 PM
 */
@Service
@Slf4j
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 地址清单
     *
     * @return
     */
    @Override
    public List<Address> list() {//select * from address_book where user_id =?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(qw);
    }

    /**
     * 设置默认地址
     * @param id
     */
    @Override
    public void defaultAdd(Long id) {
        Address address = new Address();
        address.setIsDefault(0);
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        //更新数据库
        addressMapper.update(address,qw);

        Address address2 = new Address();
        address2.setIsDefault(1);
        address2.setId(id);
        addressMapper.updateById(address2);
    }

    /**
     * 新增地址
     * @param address
     */
    @Override
    public void addAddress(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);
        //create update time user autofill
        addressMapper.insert(address);
    }

    /**
     * 回显地址
     * @param id
     * @return
     */
    @Override
    public Address getAdd(Long id) {
        return addressMapper.selectById(id);
    }

    /**
     * 修改更新地址
     * @param address
     */
    @Override
    public void updateAdd(Address address) {
        addressMapper.updateById(address);
    }

    /**
     * 获取默认地址
     * @return
     */
    @Override
    public Address getDefault() {
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        qw.eq(Address::getIsDefault,1);

        return addressMapper.selectOne(qw);
    }
}
